package cmd

import (
	"crypto/rand"
	"fmt"
	"golang.org/x/crypto/chacha20poly1305"
)

// ChaChaEncrypt 加密
func ChaChaEncrypt(password, plaintext []byte) ([]byte, error) {
	// 生成随机的加密密钥
	key := make([]byte, chacha20poly1305.KeySize)
	if _, err := rand.Read(key); err != nil {
		return nil, err
	}

	// 加密数据
	cipher, err := chacha20poly1305.New(key)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, cipher.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	ciphertext := cipher.Seal(nil, nonce, plaintext, nil)

	// 将密钥和密文拼接在一起
	return append(key, append(nonce, ciphertext...)...), nil
}

// ChaChaDecrypt 解密
func ChaChaDecrypt(password, ciphertext []byte) ([]byte, error) {
	if len(ciphertext) < chacha20poly1305.KeySize+chacha20poly1305.NonceSize {
		return nil, fmt.Errorf("invalid ciphertext")
	}

	key := ciphertext[:chacha20poly1305.KeySize]
	nonce := ciphertext[chacha20poly1305.KeySize : chacha20poly1305.KeySize+chacha20poly1305.NonceSize]
	ciphertext = ciphertext[chacha20poly1305.KeySize+chacha20poly1305.NonceSize:]

	cipher, err := chacha20poly1305.New(key)
	if err != nil {
		return nil, err
	}

	plaintext, err := cipher.Open(nil, nonce, ciphertext, nil)
	if err != nil {
		return nil, err
	}

	return plaintext, nil
}
